package org.chronologger.poppaea.client.widgets;

import java.util.ArrayList;
import java.util.List;

import org.chronologger.poppaea.client.utils.HasColor;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Grid;

public class ColorPicker extends ArrowPopupPanel {

	public static String colors[] = new String[] { 
		"black", "darkgray", "gray", "white",
		"red", "#e2001a", "#e95d0f", "#f8b356",
		"#fff15f", "#b4a400", "#887e00", "#4d6811", 
		"#287621", "#41a62a", "#47ad68", "#30b3ad", 
		"#00b9e9", "#009ee0", "#004a99", "#172983"
	};
	
	public static int ROWS = 5;
	public static int COLS = 4;
	
	private final boolean autoClose;
	private final List<HasColor> colorCallbacks;
	private final ClickHandler onClick = new ClickHandler() {
		
		public void onClick(ClickEvent event) {
			for(HasColor callback : colorCallbacks) {
				callback.setColor(event.getRelativeElement().getStyle().getProperty("backgroundColor"));
			}
			if(autoClose) {
				hide();
			}
		}
	};

	public ColorPicker(List<HasColor> callbacks, boolean autoClose) {
		this.colorCallbacks = callbacks;
		this.autoClose = autoClose;
		
		Grid colorGrid = new Grid(ROWS, COLS);
		colorGrid.setSize(COLS * 22 + "px", ROWS * 22 + "px");
		colorGrid.setCellPadding(0);
		colorGrid.setCellSpacing(0);
		getContentPanel().add(colorGrid);
		for(int i = 0; i < colors.length; i++) {
			SegmentedButton colorButton = new SegmentedButton();
			colorButton.setColor(colors[i]);
			colorButton.setHoverColor(colors[i]);
			colorButton.addSegment("").addClickHandler(onClick);
			colorButton.setSegmentSize(0, 16, 16);
			colorGrid.setWidget(i / COLS, i % COLS, colorButton);
		}
	}
	
	private static List<HasColor> callbackToList(HasColor callback) {
		List<HasColor> callbacks = new ArrayList<HasColor>();
		callbacks.add(callback);
		return callbacks;
	}
	
	public ColorPicker(HasColor callback, boolean autoClose) {
		this(callbackToList(callback), autoClose);
	}

	public void pointAt(int xleft, int xright, int y) {
		pointAt(xleft, xright, y, COLS * 22, ROWS * 22);
	}
	
	public static ClickHandler createClickHandler(final SegmentedButton colorButton) {
		return new ClickHandler() {
			
			public void onClick(ClickEvent event) {
				ColorPicker newColorPicker = new ColorPicker(colorButton, true);
				int xright = colorButton.getAbsoluteLeft() + colorButton.getOffsetWidth() - 5;
				int xleft = colorButton.getAbsoluteLeft() + 5;
				int y = colorButton.getAbsoluteTop() + colorButton.getOffsetHeight() / 2;
				newColorPicker.pointAt(xleft, xright, y);
			}
		};
	}
	
}
